package com.example.sxt_practise.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author gaofeng
 * @date 2022年06月04日 21:34
 */
public class BlockingQueueTest {
    public static void main(String[] args) {
        test2();
    }

    /**
     * 抛出异常
     */
    public static void test1() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3) ;

        System.out.println(queue.add(1));
        System.out.println(queue.add(2));
        System.out.println(queue.add(3));
        System.out.println(queue.element());
        // java.lang.IllegalStateException: Queue full
//        System.out.println(queue.add(4));

        System.out.println("+++++++++++++++++++++++++");

        System.out.println(queue.remove());
        System.out.println(queue.element());
        System.out.println(queue.remove());
        System.out.println(queue.remove());
        // java.util.NoSuchElementException
//        System.out.println(queue.remove());
    }

    /**
     * 有返回值,不抛异常
     */
    public static void test2() {
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3) ;

        System.out.println(queue.offer(1));
        System.out.println(queue.offer(2));
        System.out.println(queue.offer(3));
        System.out.println(queue.offer(4));
        System.out.println(queue.peek());
        System.out.println("+++++++++++++++++++++++++");

        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
    }

    /**
     * 一直阻塞
     */
    public static void test3() throws Exception{
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3) ;

        queue.put(1) ;
        queue.put(2) ;
        queue.put(4) ;
        queue.put(4) ;

        System.out.println("+++++++++++++++++++++++++");

        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
        System.out.println(queue.take());
    }

    /**
     * 阻塞, 等待超时
     */
    public static void test4() throws Exception{
        ArrayBlockingQueue queue = new ArrayBlockingQueue(3) ;

        queue.offer(1, 2, TimeUnit.SECONDS) ;
        queue.offer(2, 2, TimeUnit.SECONDS) ;
        queue.offer(4, 2, TimeUnit.SECONDS) ;
        queue.offer(4, 2, TimeUnit.SECONDS) ;

        System.out.println("+++++++++++++++++++++++++");

        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
        System.out.println(queue.poll(2, TimeUnit.SECONDS));
    }
}
